/**
 * @file letter_shell.c
 * @author your name (you@domain.com)
 * @brief 
 * @version 0.1
 * @date 2023-05-06
 * 
 * @copyright Copyright (c) 2023
 * 
 * @brief letter shell 功能实现
 */
 

/**
 * @brief shellWrite
 * 
 */
void ShellWrite(const char data)
{
    sShellUart.pcTrsBuffer[sShellUart.usTrsTail++] = data;
    sShellUart.usTrsTail = sShellUart.usTrsTail >= TRS_QUEUE_SIZE ? 0 : sShellUart.usTrsTail;
    usart_interrupt_enable(USART1, USART_INT_TBE);
}

/**
 * @brief letter shell 初始化
 * 
 */
void LetterShellInit(void)
{
    /* enable USART clock */
    rcu_periph_clock_enable(RCU_USART1);

    /* USART interrupt configuration */
    nvic_irq_enable(USART1_IRQn, 0, 0);

    /* connect port to USARTx_Tx */
    gpio_af_set(DEBUG_TX_PORT, GPIO_AF_1, DEBUG_TX_PIN);

    /* connect port to USARTx_Rx */
    gpio_af_set(DEBUG_RX_PORT, GPIO_AF_1, DEBUG_RX_PIN);

    /* configure USART Tx as alternate function push-pull */
    gpio_mode_set(DEBUG_TX_PORT, GPIO_MODE_AF, GPIO_PUPD_PULLUP, DEBUG_TX_PIN);
    gpio_output_options_set(DEBUG_TX_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_10MHZ, DEBUG_TX_PIN);

    /* configure USART Rx as alternate function push-pull */
    gpio_mode_set(DEBUG_RX_PORT, GPIO_MODE_AF, GPIO_PUPD_PULLUP, DEBUG_RX_PIN);
    gpio_output_options_set(DEBUG_RX_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_10MHZ, DEBUG_RX_PIN);

    /* USART configure */
    usart_deinit(USART1);
    usart_baudrate_set(USART1, 115200U);
    usart_transmit_config(USART1, USART_TRANSMIT_ENABLE);
    usart_receive_config(USART1, USART_RECEIVE_ENABLE);
    usart_enable(USART1);
	
	/* disable USART TBE interrupt */  
    usart_interrupt_disable(USART1, USART_INT_TBE);

    /* enable USART RBNE interrupt */  
    usart_interrupt_enable(USART1, USART_INT_RBNE);

    shell.write = ShellWrite;
    shellInit(&shell, shellBuffer, sizeof(shellBuffer));
}


/*!
    \brief      this function handles USART RBNE interrupt request and TBE interrupt request
    \param[in]  none
    \param[out] none
    \retval     none
*/
void USART1_IRQHandler(void)
{
    if(RESET != usart_interrupt_flag_get(USART1, USART_INT_FLAG_RBNE))
    {
        /* receive data */
        shellHandler(&shell, (char)usart_data_receive(USART1));
    }
	
	if(RESET != usart_interrupt_flag_get(USART1, USART_INT_FLAG_TBE)){
        /* transmit data */
        usart_data_transmit(USART1, sShellUart.pcTrsBuffer[sShellUart.usTrsHead++]);
        sShellUart.usTrsHead = sShellUart.usTrsHead >= TRS_QUEUE_SIZE ? 0 : sShellUart.usTrsHead;
        if(sShellUart.usTrsHead == sShellUart.usTrsTail){
            usart_interrupt_disable(USART1, USART_INT_TBE);
        }
    }
}
